package com.daxia.bumall.web.controller.m;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.daxia.bumall.common.AuditStatus;
import com.daxia.bumall.common.MyJSONObject;
import com.daxia.bumall.common.NeedLogin;
import com.daxia.bumall.common.Sex;
import com.daxia.bumall.common.ToBeDone;
import com.daxia.bumall.common.UserType;
import com.daxia.bumall.dto.CityDTO;
import com.daxia.bumall.dto.DesignDTO;
import com.daxia.bumall.dto.DesignerDTO;
import com.daxia.bumall.dto.TimelineDTO;
import com.daxia.bumall.dto.UserDTO;
import com.daxia.bumall.dto.UserHeadImagesDTO;
import com.daxia.bumall.dto.api.DesignerAPIDTO;
import com.daxia.bumall.exception.BizException;
import com.daxia.bumall.model.City;
import com.daxia.bumall.model.Designer;
import com.daxia.bumall.model.User;
import com.daxia.bumall.support.MPage;
import com.daxia.bumall.support.Page;

@Controller
@RequestMapping(value = "/m/designer", produces = "application/json;charset=UTF-8")
public class MDesignerController extends MBaseController implements IAPIConerter<DesignerDTO, DesignerAPIDTO> {
	
	private static Logger logger = Logger.getLogger(MDesignerController.class);
	
	@ResponseBody
	@RequestMapping("list")
	public String list(DesignerDTO dto,Long cityId, MPage page) throws Exception {

		MyJSONObject data = new MyJSONObject();
		JSONArray designerInfos = new JSONArray();
		dto.setAuditStatus(AuditStatus.Success.getValue());
		if (cityId != null) {
			CityDTO cityDTO = cityService.load(cityId);
			if (cityDTO != null) {
				City city = new City();
				city.setId(cityId);
				dto.setCity(city);
			}
		}
		List<DesignerDTO> designerDTOs = designerService.find(dto, page);
		for (DesignerDTO designerDTO : designerDTOs) {
			DesignDTO designQuery = new DesignDTO();
			designQuery.setUser(new User(designerDTO.getUser().getId()));
			List<DesignDTO> designList = designService.find(designQuery, null);
			if (CollectionUtils.isEmpty(designList)) {
				continue;
			}
			
			MyJSONObject designerInfo = new MyJSONObject();
			designerInfo.put("id", designerDTO.getId());
			designerInfo.put("userId", designerDTO.getUser().getId());
			designerInfo.put("headImage", designerDTO.getUser().getHeadImage());
			designerInfo.put("username", designerDTO.getUser().getUsername());
			designerInfo.put("nickName", designerDTO.getUser().getNickName());
			designerInfo.put("dealCount", designerDTO.getDealCount());
			String[] imgs = {};
			String images = designerDTO.getTopDesignerImage();
			if (StringUtils.isNotBlank(images)) {
				imgs = images.split(",");
			}
			if (ArrayUtils.isEmpty(imgs)) {
				List<DesignDTO> designs = designService.findByUserId(designerDTO.getUser().getId(), 1);
				if (CollectionUtils.isNotEmpty(designs)) {
					DesignDTO d = designs.get(0);
					if (CollectionUtils.isNotEmpty(d.getImageList())) {
						imgs = new String[] {d.getImageList().get(0)};
					};
				}
			}
			designerInfo.put("topDesignerImage", imgs);
			designerInfo.put("sex", designerDTO.getUser().getSex());
			designerInfo.put("sexRemark", Sex.getByValue(designerDTO.getUser().getSex()).getRemark());
			designerInfo.put("latitude", designerDTO.getUser().getLatitude());
			designerInfo.put("longitude", designerDTO.getUser().getLongitude());

			designerInfos.add(designerInfo);
		}

		data.put("designerInfos", designerInfos);
		return toJson(data);
	}

	private JSONArray toDesignersJson(List<DesignerDTO> designerDTOs) {
		JSONArray array = new JSONArray();
		for (DesignerDTO designerDTO : designerDTOs) {
			array.add(toDesignerAPIDTO(designerDTO));
		}
		return array;
	}

	private DesignerAPIDTO toDesignerAPIDTO(DesignerDTO dto) {
		User user = dto.getUser();
		DesignerAPIDTO apidto = new DesignerAPIDTO();
		apidto.setId(dto.getId());
		apidto.setHeadImage(user.getHeadImage());
		apidto.setUsername(user.getUsername());
		apidto.setDealCount(dto.getDealCount());
		apidto.setTopDesignerImage(dto.getTopDesignerImage());
		apidto.setSex(user.getSex());
		apidto.setSexRemark(Sex.getByValue(user.getSex()).getRemark());

		return apidto;
	}

	/**
	 * 推荐设计师
	 * 
	 * @param dto
	 * @param page
	 * @return
	 * @throws Exception
	 */
	@ToBeDone
	// @NeedLogin
	@ResponseBody
	@RequestMapping("recommend")
	public String recommend(DesignerDTO dto, Long userId, Long cityId, String cityName, Long houseStyleId, Long houseTypeId, MPage page) throws Exception {
		logger.info("cityID : " + cityId + "houseStyleId : " + houseStyleId + "houseTypeId" + houseTypeId);
		MyJSONObject data = new MyJSONObject();
		JSONArray designerInfos = new JSONArray();
		
		if (cityId != null) {
			CityDTO cityDTO = cityService.load(cityId);
			if (cityDTO != null) {
				City city = new City();
				city.setId(cityId);
				dto.setCity(city);
			}
		}
		List<DesignerDTO> designerDTOs = designerService.find(dto, page);
		for (DesignerDTO designerDTO : designerDTOs) {
			
			// 设计作品为空不推荐
			DesignDTO designQuery = new DesignDTO();
			Designer designerQuery = new Designer();
			designerQuery.setId(designerDTO.getId());
			designQuery.setDesigner(designerQuery);
			List<DesignDTO> designList = designService.find(designQuery, null);
			if (CollectionUtils.isEmpty(designList)) {
				continue;
			}
			
			MyJSONObject designerInfo = new MyJSONObject();
			designerInfo.put("id", designerDTO.getId());
			designerInfo.put("userId", designerDTO.getUser().getId());
			designerInfo.put("headImage", designerDTO.getUser().getHeadImage());
			designerInfo.put("username", designerDTO.getUser().getUsername());
			designerInfo.put("nickName", designerDTO.getUser().getNickName());
			designerInfo.put("dealCount", designerDTO.getDealCount());
			String[] imgs = {};
			String images = designerDTO.getTopDesignerImage();
			if (StringUtils.isNotBlank(images)) {
				imgs = images.split(",");
			}
			if (ArrayUtils.isEmpty(imgs)) {
				List<DesignDTO> designs = designService.findByUserId(designerDTO.getUser().getId(), 1);
				if (CollectionUtils.isNotEmpty(designs)) {
					DesignDTO d = designs.get(0);
					if (CollectionUtils.isNotEmpty(d.getImageList())) {
						imgs = new String[] {d.getImageList().get(0)};
					};
				}
			}
			designerInfo.put("topDesignerImage", imgs);
			designerInfo.put("sex", designerDTO.getUser().getSex());
			designerInfo.put("sexRemark", Sex.getByValue(designerDTO.getUser().getSex()).getRemark());
			designerInfo.put("latitude", designerDTO.getUser().getLatitude());
			designerInfo.put("longitude", designerDTO.getUser().getLongitude());
			designerInfo.put("cityId", cityId);

			designerInfos.add(designerInfo);
		}

		data.put("designerInfos", designerInfos);
		return toJson(data);
	}

	@Override
	public DesignerAPIDTO fromDTO2APIDTO(DesignerDTO dto) {

		User user = dto.getUser();
		DesignerAPIDTO apidto = new DesignerAPIDTO();
		apidto.setId(dto.getId());
		apidto.setHeadImage(user.getHeadImage());
		apidto.setUsername(user.getUsername());
		apidto.setDealCount(dto.getDealCount());
		apidto.setTopDesignerImage(dto.getTopDesignerImage());
		apidto.setSex(user.getSex());
		apidto.setSexRemark(Sex.getByValue(user.getSex()).getRemark());

		return apidto;

	}

	/**
	 * 
	 * @param designerId
	 * @param longitude 经度
	 * @param latitude 纬度
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping("detail")
	public String detail(Long designerId, Long longitude, Long latitude) throws Exception {
		logger.info("designer id is : " + designerId.toString());
		JSONObject data = new JSONObject();

		JSONArray headImages = new JSONArray();
		
		DesignerDTO designerDTO = designerService.load(designerId);
		if (designerDTO != null) {
			throw new BizException("can not find designer info by designer id " + designerId);
		}
		
		List<UserHeadImagesDTO> userHeadImageList = userHeadImagesService.findAll();
		for (UserHeadImagesDTO userHeadImageDTO : userHeadImageList) {
			headImages.add(userHeadImageDTO.getHeadImage());
		}
		data.put("headImages", headImages);
		data.put("username", designerDTO.getUser().getUsername());
		data.put("nickName", designerDTO.getUser().getNickName());
		data.put("sex", designerDTO.getUser().getSex());
		data.put("sexRemark", Sex.getByValue(designerDTO.getUser().getSex()).getRemark());
		data.put("distance", "0.06km");
		data.put("lastOnLine", "2分钟");
		
		TimelineDTO timelineQuery = new TimelineDTO();
		Page page = new Page();
		List<TimelineDTO> timelineList = timelineService.find(timelineQuery , page);

		JSONArray timelineImages = new JSONArray();
		timelineImages.add("http://h.hiphotos.baidu.com/image/pic/item/78310a55b319ebc468f95b648726cffc1f17164d.jpg");
		timelineImages.add("http://a.hiphotos.baidu.com/image/pic/item/d000baa1cd11728b2758d8dfcdfcc3cec2fd2cd1.jpg");
		timelineImages.add("http://news.yule.com.cn/uploadfile/2016/0920/20160920010952183.jpg");
		data.put("timelineImages", timelineImages);
		data.put("level", "1");
		data.put("levelRemark", "普通会员");
		data.put("sign", "我就是我，不一样的烟火");

		data.put("company", designerDTO.getCompany());
		data.put("workAge", designerDTO.getWorkAge());
		data.put("serviceArea", designerDTO.getServiceArea());
		data.put("goodAtStyles", designerDTO.getGoodAtStyles());
		data.put("relation", "陌生人");

		JSONArray designImages = new JSONArray();
		designImages.add("http://pic17.nipic.com/20111118/8030602_090358387000_2.jpg");
		designImages.add("http://img02.tooopen.com/images/20151224/tooopen_sy_152619386585.jpg");
		designImages.add("http://pic83.huitu.com/res/20160807/87190_20160807133324868373_1.jpg");
		designImages.add("http://img0.imgtn.bdimg.com/it/u=2234379552,314504988&fm=21&gp=0.jpg");
		designImages.add("http://img5.imgtn.bdimg.com/it/u=2080030473,2595691176&fm=21&gp=0.jpg");
		data.put("designImages", designImages);

		return toJson(data);
	}

	/**
	 * 增加关注
	 * 
	 * @return
	 * @throws Exception
	 */
	@NeedLogin
	@ResponseBody
	@RequestMapping("addFan")
	public String addFan(Long designerId) throws Exception {
		return toJson();
	}

	/**
	 * 取消关注
	 * 
	 * @return
	 * @throws Exception
	 */
	@NeedLogin
	@ResponseBody
	@RequestMapping("cancelFan")
	public String cancelFan(Long designerId) throws Exception {
		return toJson();
	}
	
	
	@NeedLogin
	@ResponseBody
	@RequestMapping("auth/detail")
	public String authDetail() throws Exception {
		MyJSONObject data = new MyJSONObject();
		User user = getCurrentUser();
		
		List<Designer> designers = user.getDesigners();
		if (CollectionUtils.isNotEmpty(designers)) {
			Designer designer = designers.get(0);
			data.put("realName", user.getRealName());
			data.put("nickName", user.getNickName());
			data.put("username", user.getUsername());
			data.put("age", user.getAge());
			data.put("sex", user.getSex());
			data.put("auditStatus", designer.getAuditStatus());
			data.put("auditStatusRemark", AuditStatus.getByValue(designer.getAuditStatus()).getRemark());
			data.put("workAge", designer.getWorkAge());
			data.put("workPlace", designer.getWorkPlace());
			data.put("serviceArea", designer.getServiceArea());
			data.put("goodStyles", designer.getGoodAtStyles());
			data.put("company", designer.getCompany());
			String[] images = {};
			String designImages = designer.getDesignImages();
			if (StringUtils.isNotBlank(designImages)) {
				images = designImages.split(",");
			}
			data.put("images", images);
		}
		
		return toJson(data);
	}
	

	@Transactional
	@NeedLogin
	@ResponseBody
	@RequestMapping("authentication")
	public String authentication(String realName, Integer age, Integer sex, DesignerDTO designerDTO,
			HttpServletRequest request) throws Exception {
		String images = super.saveFilesAndReturnFileName(request);
		MyJSONObject data = new MyJSONObject();

		UserDTO currentUser = getCurrentUserDTO();
		UserDTO userDTO = userService.load(currentUser.getId());
		User user = new User();
		BeanUtils.copyProperties(currentUser, user);
		userDTO.setRealName(realName);
		userDTO.setSex(sex);
		userDTO.setAge(age);
		userDTO.setType(UserType.Designer.getValue());

		userService.updateAllFields(userDTO);

		DesignerDTO designQuery = new DesignerDTO();
		User userQuery =new User();
		userQuery.setId(user.getId());
		designQuery.setUser(userQuery);
		DesignerDTO designerDTO2 = designerService.findOne(designQuery);
		if (designerDTO2 == null) {
			designerDTO2 = new DesignerDTO();
			designerDTO2.setWorkAge(designerDTO.getWorkAge());
			designerDTO2.setCompany(designerDTO.getCompany());
			designerDTO2.setServiceArea(designerDTO.getServiceArea());
			designerDTO2.setGoodAtStyles(designerDTO.getGoodAtStyles());
			
			designerDTO2.setDesignImages(images);
			designerDTO2.setUser(user);
			
			if (designerDTO.getProvince() != null && designerDTO.getProvince().getId() != null) {
				designerDTO2.setProvince(designerDTO.getProvince());
			}
			if (designerDTO.getCity() != null && designerDTO.getCity().getId() != null) {
				designerDTO2.setCity(designerDTO.getCity());
			}
			if (designerDTO.getDistrict() != null && designerDTO.getDistrict().getId() != null) {
				designerDTO2.setDistrict(designerDTO.getDistrict());
			}
			
			designerDTO2.setWorkPlace(parseWorkPlace(designerDTO2));
			designerService.create(designerDTO2);
		} else {
			
			designerDTO2.setWorkAge(designerDTO.getWorkAge());
			designerDTO2.setCompany(designerDTO.getCompany());
			designerDTO2.setServiceArea(designerDTO.getServiceArea());
			designerDTO2.setGoodAtStyles(designerDTO.getGoodAtStyles());
			
			if (designerDTO.getProvince() != null && designerDTO.getProvince().getId() != null) {
				designerDTO2.setProvince(designerDTO.getProvince());
			}
			if (designerDTO.getCity() != null && designerDTO.getCity().getId() != null) {
				designerDTO2.setCity(designerDTO.getCity());
			}
			if (designerDTO.getDistrict() != null && designerDTO.getDistrict().getId() != null) {
				designerDTO2.setDistrict(designerDTO.getDistrict());
			}
			
			designerDTO2.setWorkPlace(parseWorkPlace(designerDTO2));
			
			designerDTO2.setDesignImages(images);
			
			designerDTO2.setAuditStatus(AuditStatus.NotAudit.getValue());
			designerService.updateAllFields(designerDTO2);
		}

		return toJson(data);
	}

	private String parseWorkPlace(DesignerDTO dto) {
		String s = "";
		if (dto.getProvince() != null && dto.getProvince().getId() != null) {
			s += provinceService.load(dto.getProvince().getId()).getName();
		}
		if (dto.getCity() != null && dto.getCity().getId() != null) {
			s += cityService.load(dto.getCity().getId()).getName();
		}
		if (dto.getDistrict() != null && dto.getDistrict().getId() != null) {
			s += districtService.load(dto.getDistrict().getId()).getName();
		}
		return s;
	}

}
